import { AppTokenObj } from "../dao/AppToken"
import { renderSelectParam, renderSelectSql } from "../utils/renderSql"
import { ReposBase } from "./RepoBase"

export type CollectParma = {
  teaId?: number
  teaName?: string
  collectId?: number
}

export type AddCollectParam = {
   teaId: number
}

export class CollectRepository  extends ReposBase {
  private static inst: CollectRepository

  // 单例
  public static getInstance() {
    if (!CollectRepository.inst) {
      CollectRepository.inst = new CollectRepository()
    }

    return CollectRepository.inst
  }

  collect(params: CollectParma, customer: number) {
    const config: renderSelectParam = {
      database: [
        { name: 'collects', aliasName: "co" },
        { name: "commodities", aliasName: 'c' },
        { name: "tea_types", aliasName: 't' }
      ],
      returnFeild: [
        { name: "co.tea_id", aliasName: "teaId" },
        { name: 'c.tea_name', aliasName: 'teaName' },
        "cover",
        { name: 't.type_name', aliasName: 'typeName' },
        { name: 'c.tea_type', aliasName: 'teaType' },
        "price",
        { name: 'co.collect_id', aliasName: 'collectId' },
      ],
      where: [
        { key: 'c.tea_type', sqlVal: 't.type_id', isDatabase: true },
        { key: 'co.tea_id', sqlVal: 'c.tea_id', isDatabase: true },
        { key: 'co.customer', sqlVal: customer },
      ],
      like:[]
    }

    if (params.teaId) {
      config.where.push(
        { key: 'co.tea_id', sqlVal: params.teaId }
      )
    }

    if (params.collectId) {
      config.where.push(
        { key: 'co.collect_id', sqlVal: params.collectId }
      )
    }

    const sql = renderSelectSql(config)
    return this.query<{collectId:number}>(sql)
  }

  addCollect(params: AddCollectParam, customer: AppTokenObj["userId"]) {
    const sql = `INSERT INTO collects(tea_id, customer) VALUES(${params.teaId}, ${customer})`
    
    return this.insert(sql)
  }

  delCollect(collectId: number, customer: AppTokenObj["userId"]) { 
    const sql = `DELETE FROM collects WHERE collect_id = ${collectId}`

    return this.delete(sql)
  }
}